package com.fishingwithme.android.ui.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fishingwithme.android.data.model.RuleItem
import com.fishingwithme.android.data.repository.FishingRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class CreditRulesViewModel @Inject constructor(
    private val repository: FishingRepository
) : ViewModel() {

    private val _uiState = MutableStateFlow<CreditRulesUiState>(CreditRulesUiState.Loading)
    val uiState: StateFlow<CreditRulesUiState> = _uiState

    init {
        loadCreditRules()
    }

    fun loadCreditRules() {
        viewModelScope.launch {
            _uiState.value = CreditRulesUiState.Loading
            repository.getCreditRules()
                .catch { e ->
                    _uiState.value = CreditRulesUiState.Error(e.message ?: "Failed to load credit rules")
                }
                .collect { result ->
                    result.fold(
                        onSuccess = { rules ->
                            // Group rules by level range
                            val groupedRules = rules.groupBy { rule ->
                                if (rule.levelRangeStart == rule.levelRangeEnd) {
                                    rule.levelRangeStart.toString()
                                } else {
                                    "${rule.levelRangeStart}-${rule.levelRangeEnd}"
                                }
                            }
                            _uiState.value = CreditRulesUiState.Success(groupedRules)
                        },
                        onFailure = { error ->
                            _uiState.value = CreditRulesUiState.Error(error.message ?: "Failed to load credit rules")
                        }
                    )
                }
        }
    }

    fun retry() {
        loadCreditRules()
    }
}

sealed class CreditRulesUiState {
    object Loading : CreditRulesUiState()
    data class Success(val groupedRules: Map<String, List<RuleItem>>) : CreditRulesUiState()
    data class Error(val message: String) : CreditRulesUiState()
}